﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aliyun.MQS.SDK
{
    public class PluginManager
    {
        private readonly IDictionary<RuntimeTypeHandle, IPlugin> _pluginDict = new Dictionary<RuntimeTypeHandle, IPlugin>();
        private PluginManager()
        {
            this.Register<IEncodingPlugin>(new UTF8EcondingPlugin());
            this.Register<ICommonHeaderPlugin>(new DefaultCommonHeaderPlugin());
        }

        public void Register<T>(T plugin) where T : IPlugin
        {
            var typeHandle = typeof(T).TypeHandle;
            if (_pluginDict.ContainsKey(typeHandle))
            {
                _pluginDict[typeHandle] = plugin;
            }
            else
            {
                _pluginDict.Add(typeHandle, plugin);
            }
        }

        public T Resolve<T>() where T : IPlugin
        {
            var typeHandle = typeof(T).TypeHandle;
            return (T)_pluginDict[typeHandle];
        }

        private static Lazy<PluginManager> _instance = new Lazy<PluginManager>(() => new PluginManager(), true);
        public static PluginManager Instance
        {
            get
            {
                return _instance.Value;
            }
        }
    }
}
